package org.bpms.config;


import java.util.Map;

import org.beetl.core.GroupTemplate;
import org.beetl.ext.jfinal.BeetlRenderFactory;
import org.bpms.handler.BpmsHandler;
import org.bpms.interceptor.GlobalInterceptor;
import org.bpms.interceptor.WebInterceptor;
import org.bpms.model.wechat.Weixin;
import org.bpms.plugins.bjui.SchedulerPlugin;
import org.bpms.plugins.tablebind.AutoTableBindPlugin;
import org.bpms.plugins.tablebind.SimpleNameStyles;
import org.bpms.routes.AdminRoutes;
import org.bpms.routes.WeixinRoutes;
import org.bpms.service.admin.MemberService;
import org.bpms.service.wechat.WeixinService;

import com.jfinal.aop.Enhancer;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.plugin.redis.RedisPlugin;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.UserApi;

import cn.dreampie.sqlinxml.SqlInXmlPlugin;
import cn.dreampie.sqlinxml.SqlKit;

/**
 * jfinal配置器
 * @author hupei
 *
 */
public class BpmsConfig extends JFinalConfig{
	private WeixinService weixinService = Enhancer.enhance(WeixinService.class);
	private MemberService memberService = Enhancer.enhance(MemberService.class);
	public static C3p0Plugin c3p0Plugin;
	@Override
	public void configConstant(Constants me) {
		PropKit.use("config.properties");//加载配置文件
		me.setDevMode(PropKit.getBoolean("devMode"));//开发者模式
		//me.setViewType(ViewType.JSP);//以jsp为视图文件
		me.setEncoding("UTF-8");
		//beetl模板
		me.setMainRenderFactory(new BeetlRenderFactory());
		GroupTemplate groupTemplate = BeetlRenderFactory.groupTemplate;
		
		//文件上传最大多少，这里设置300M
		me.setMaxPostSize(300 * 1024 * 1024);
	}

	@Override
	public void configHandler(Handlers me) {
		me.add(new BpmsHandler());
	}

	@Override
	public void configInterceptor(Interceptors me) {
		me.add(new GlobalInterceptor());
		me.add(new WebInterceptor());
	}

	@Override
	public void configPlugin(Plugins me) {
		Prop p = PropKit.use("config.properties");//非第一次使用该配置文件
		//加载数据库配置
		c3p0Plugin = new C3p0Plugin(p.get("jdbc_url"), 
				p.get("jdbc_username"), p.get("jdbc_password"));
		me.add(c3p0Plugin);
		//自动扫描model，绑定table
		AutoTableBindPlugin arp = new AutoTableBindPlugin(c3p0Plugin , SimpleNameStyles.LOWER);
		me.add(arp);
		
		
		//sql语句plugin---复杂的sql语句可以用xml文件管理起来
		//me.add(new SqlInXmlPlugin("mysql"));
		
	    //Quartz调度插件---配合snaker工作流，使用数据库来持久化
//	    QuartzPlugin quartzPlugin = new QuartzPlugin();
//	    me.add(quartzPlugin);
	    
	    //简单任务调度--内存持有，无持久化
	    SchedulerPlugin sp = new SchedulerPlugin("job.properties");
	    //添加插件
	    me.add(sp);
	    
	  //使用redis缓存方案时使用weixin作为主缓存，打开连接
	    if (p.getBoolean("redis_mode")){
			RedisPlugin weixinPlugin = new RedisPlugin("weixin", p.get("redis_host"), p.get("redis_pass"));
			me.add(weixinPlugin);
	    }
	    
	    me.add(new EhCachePlugin());
	}

	@Override
	public void configRoute(Routes me) {
		me.add(new AdminRoutes());
		me.add(new WeixinRoutes());
	}

	@Override
	public void afterJFinalStart() {
		ApiConfigKit.setThreadLocalApiConfig(getApiConfig());
		ApiResult result =  UserApi.getFollows();
		com.alibaba.fastjson.JSONObject obj = result.get("data");
		for (Object openid : obj.getJSONArray("openid")){
			ApiResult apiResult = UserApi.getUserInfo((String)openid);
			memberService.saveOrUpdate(apiResult);
		}	
		super.afterJFinalStart();
	}
	
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();
		Prop p = PropKit.use("config.properties");
		Weixin weixin = weixinService.find();
		if (null != weixin){
			// 配置微信 API 相关常量
			ac.setAppId(weixin.getStr("appid"));
			ac.setAppSecret(weixin.getStr("appsecret"));
			ac.setToken(weixin.getStr("token"));
			if (null != weixin.getStr("encodingaeskey") && !weixin.getStr("encodingaeskey").equals("")){
				ac.setEncryptMessage(true);
				ac.setEncodingAesKey(weixin.getStr("encodingaeskey"));
			}
			if (p.getBoolean("redis_mode")){
				ac.setIsredis(true);
			}
			return ac;
		}
		return null;
	}
}
